<template>
  <div class="comp">
    <div class="chart" ref="huan">我是组件</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      echartes: null, //实裂对象
      allData: [], //业务数据
    };
  },
  methods: {
    //1.获取eacharts实裂对象  设置基础静态配置项 制基础图标
    initEcharts() {
      //1.1获取eacharts实裂对象
      this.echartes = this.$echarts.init(this.$refs.huan, "dark");
      //1.2设置基础静态配置项
      let initOptions = {
        //标题
        title: {
          text: "▎主要农作物种植占比",
          top: "3%",
          left: "3%",
        },
        //坐标xi
        grid: {
          // show: true,
          top: "8%",
          lef: "3%",
          containLabel: true,
        },
        //提示语
        tooltip: {
          show: true,
        },
        //系列
      };

      //1.3绘制基础图标
      this.echartes.setOption(initOptions);
    },
    //获取业务数据
    async getData() {
      let { data } = await this.$http.get("cropAreasProportion");
      this.allData = data;
      console.log(data);
      //根据数据绘制图表
      this.setEcharts();

      // //4.使用适配
      this.Adaptive();
    },
    //根据数据绘制图表
    setEcharts() {
      //3.3根据数据系列生成配置
      let count = this.allData.length;
      let seriseDate = this.allData.map((item, index) => {
        //返回绘制的每个系列对象
        return {
          type: "pie",
          radius: [60, 80],
          label: {
            position: "center",
          },
          data: [
            { name: item.areas + "\n" + item.zb + "%", value: item.zb },
            { name, value: item.other },
          ],
          center: [(100 / (count + 1)) * (index + 1) + "%", "60%"],
        };
      });
      let setOptions = {
        //系列
        series: seriseDate,
      };

      //绘制图表
      this.echartes.setOption(setOptions);
    },
    //4.0适配方法
    Adaptive() {
      //获取一个比列尺
      let width = this.$refs.huan.offsetWidth;
      let scale = (width / 100) * 3.6;

      let seriseDate = this.allData.map((item, index) => {
        //返回绘制的每个系列对象
        return {
          //文本大小
          label: {
            fontSize: scale / 2,
          },
          radius: [scale * 1.3, scale * 1.5],
        };
      });
      //根据比列尺动态
      let updataOptions = {
        //标题
        title: {
          textStyle: {
            fontSize: scale,
          },
        },
        //系列
        series: seriseDate,
      };
      //使用动态配置绘图
      this.echartes.setOption(updataOptions);
      //只使坐标系内部图表适配
      this.echartes.resize();
    },
  },
  mounted() {
    //1.获取实裂
    this.initEcharts();
    //2.获取业务数据
    this.getData();
    // //3.监听窗口变化
    window.addEventListener("resize", this.Adaptive);
  },
  //移除监听
  destroyed() {
    window.removeEventListener("resize", this.Adaptive);
  },
};
</script>


<style>
</style>
